package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.DormManagerHis;
import com.xmy.cultivate.entity.DormRoom;
import com.xmy.cultivate.entity.DormRoomMember;
import com.xmy.cultivate.entity.DormRoomMemberHis;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 宿舍成员 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-02
 */
@RestController
@RequestMapping("/api/admin/dormRoomMember")
public class DormRoomMemberController extends BaseController{

    @Autowired
    IDormRoomService iDormRoomService;
    @Autowired
    IDormRoomMemberService iDormRoomMemberService;
    @Autowired
    IDormManagerHisService iDormManagerHisService;
    @Autowired
    IDormRoomMemberHisService iDormRoomMemberHisService;
    @Autowired
    IStaffService iStaffService;
    @Autowired
    IDictService iDictService;

    @GetMapping("/getDormRoomMemberList")
    public Result getDormRoomMemberList(
            @RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "roomId", defaultValue = "") String roomId){
        DormRoom dormRoom = iDormRoomService.getById(roomId);
        if (dormRoom == null){
            return new Result(Code.ERROR, "", "该宿舍不存在,无法查询");
        }
        IPage<DormRoomMember> iPage = new Page<>(pageNum, pageSize);
        iDormRoomMemberService.getDormRoomMemberList(iPage, roomId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


//    @GetMapping("/getDormRoomMemberListBySexType")
//    public Result getDormRoomMemberListBySexType(
//            @RequestParam(value = "SexType", defaultValue = "") String SexType){
//        QueryWrapper<DormRoomMember> queryWrapper = new QueryWrapper<>();
//
//
//        //
//        return null;
//
//
//    }

    @PostMapping("/saveDormRoomMember")
    public Result saveDormRoomMember(@RequestBody DormRoomMember dormRoomMember){
        Long roomId = dormRoomMember.getRoomId();
        DormRoom dormRoom = iDormRoomService.getById(roomId);
        if (dormRoom == null){
            return new Result(Code.ERROR, "", "该宿舍不存在,无法添加");
        }
        QueryWrapper<DormRoomMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_id", roomId);
        long count = iDormRoomMemberService.count(queryWrapper);
        if (count >= dormRoom.getBerth()){
            return new Result(Code.ERROR, "", "此宿舍已满员,不可添加宿舍成员");
        }
        dormRoomMember.setCreatedId(this.adminId);
        boolean save = iDormRoomMemberService.save(dormRoomMember);
        if (save){
            return new Result(Code.SAVE_OK, "", "添加成功");
        }
        return new Result(Code.SAVE_ERROR, "", "添加失败");
    }

    @PutMapping("/updateDormRoomMember")
    public Result updateDormRoomMember(@RequestBody DormRoomMember dormRoomMember){
        DormRoomMember existingDormRoomMember = iDormRoomMemberService.getById(dormRoomMember.getId());
        if (existingDormRoomMember == null){
            return new Result(Code.ERROR, "", "该宿舍成员不存在,无法修改");
        }
        DormRoom dormRoom = iDormRoomService.getById(dormRoomMember.getRoomId());
        if (dormRoom == null){
            return new Result(Code.ERROR, "", "该宿舍不存在,请选择其他宿舍");
        }
        Integer berth = dormRoom.getBerth();
        QueryWrapper<DormRoomMember> dormRoomMemberQueryWrapper = new QueryWrapper<>();
        dormRoomMemberQueryWrapper.eq("room_id", dormRoomMember.getRoomId());
        long count = iDormRoomMemberService.count(dormRoomMemberQueryWrapper);
        if (count >= berth){
            return new Result(Code.ERROR, "", "该宿舍已满员,请入住其他宿舍");
        }

        // 比较 roomId 是否发生变化
        boolean roomChanged = !existingDormRoomMember.getRoomId().equals(dormRoomMember.getRoomId());

        boolean update = iDormRoomMemberService.updateById(dormRoomMember);
        if (update){
            LocalDate currentDate = LocalDate.now();
            if (roomChanged) {
                DormRoomMemberHis dormRoomMemberHis = new DormRoomMemberHis();

                //转出宿舍id
                dormRoomMemberHis.setOutRoomId(existingDormRoomMember.getRoomId());
                //转入宿舍id
                dormRoomMemberHis.setInRoomId(dormRoomMember.getRoomId());
                dormRoomMemberHis.setTeacherId(dormRoomMember.getTeacherId());
                dormRoomMemberHis.setTeacherId(this.adminId);

                //转出宿舍的开始时间
                dormRoomMemberHis.setOutStartDate(existingDormRoomMember.getStartDate());
                // 判断截止时间
                if (dormRoomMember.getStartDate().isAfter(existingDormRoomMember.getStartDate())) {
                    dormRoomMemberHis.setOutEndDate(dormRoomMember.getStartDate().minusDays(1));
                } else {
                    dormRoomMemberHis.setOutEndDate(existingDormRoomMember.getStartDate());
                }

                dormRoomMemberHis.setCreatedId(this.adminId);
                iDormRoomMemberHisService.save(dormRoomMemberHis);
            }
            return new Result(Code.UPDATE_OK, "", "修改成功");
        }
        return new Result(Code.UPDATE_ERROR, "", "修改失败");
    }

    @DeleteMapping("/deleteDormRoomMember")
    public Result deleteDormRoomMember(@RequestBody DormRoomMember dormRoomMember){
        DormRoomMember dormRoomMember1 = iDormRoomMemberService.getById(dormRoomMember.getId());
        if (dormRoomMember1 == null){
            return new Result(Code.ERROR, "", "该宿舍成员不存在,无法删除");
        }
        boolean remove = iDormRoomMemberService.removeById(dormRoomMember);
        if (remove){
            return new Result(Code.DELETE_OK, "", "删除成功");
        }
        return new Result(Code.DELETE_ERROR, "", "删除失败");
    }

    //获取宿舍成员
    @GetMapping("/getDormRoomMemberListBySexType")
    public Result getDormRoomMemberListBySexType(@RequestParam(value = "SexType", defaultValue = "") String SexType //0女 1男
     ){
        // 获取当前时间
        LocalDate currentDate = LocalDate.now();
        QueryWrapper<DormRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sex_type", SexType);
        queryWrapper.eq("status", 1);
        // 查询pact_end_date_time大于等于当前时间的记录
        queryWrapper.ge("pact_end_date_time", currentDate);
        List<DormRoom> dormRoomList = iDormRoomService.list(queryWrapper);
        //获取所有id
        List<Long> roomIdList = dormRoomList.stream().map(DormRoom::getId).collect(Collectors.toList());
        String roomIds = roomIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        if (SexType.equals("0")){
            SexType = "2";
        }
        List<DormRoomMember> dormRoomMemberListBySexType = iDormRoomMemberService.getDormRoomMemberListBySexType(SexType, roomIds);
        return new Result(Code.OK, dormRoomMemberListBySexType, Code.GET_OK_MSG);



    }



}
